<?php

class Admin_Model_MBook
{
    protected $connection=null;
    private $_function=null;
    public function  __construct()
    {
       $this->connection=new Mongo();
       $this->_function=new Default_Model_MFunction();
    }

    public function isExistBook($bid)
    {
        $collection=$this->connection->bookstore->book;
        $id=new MongoId($bid);
        $doc=$collection->findOne(array("_id"=>$id));
        if($doc!=null)
            return true;
        return false;
    }
    
    //---------------------------------------------------------------------------------------------
    //----------------- Chức năng quản lý thông tin sách trong bookinterest -------------------------------------------
    //---------------------------------------------------------------------------------------------


    // Được sử dụng khi xem chi tiết một cuốn sách
    // $idBook: xác định cuốn sách nào được xem
    // $idUser: xác định ai xem cuốn sách hiện tại (trong trường hợp đã đăng nhập)
    // nếu $idUser không được truyền vào thì chỉ cộng số lượng được xem của cuốn sách hiện tại
    // nếu $idUser được truyền vào thì thêm $idBook vào danh sách những cuốn sách được xem bởi $idUser trong book_view_history
    public function addView($idBook, $idUser='')
    {
        $db=$this->connection->bookstore;
        $collection=$db->bookinterest;

        // cộng thêm số view của cuốn sách trong bookinterest
        $newIdBook= new MongoId($idBook);
        $tempBook=$collection->findOne(array("id_book"=>$newIdBook));
        if($tempBook!=null)
        {
             // thiet lap totalmark de danh gia sach duoc quan tam nhat
            $totalmark=(int)$tempBook["view"]+1+(int)$tempBook["sumcomment"]+(int)$tempBook["sumlike"]
                        +2*(int)$tempBook["sumrating"]+3*(int)$tempBook["sellnumber"];
            // thiet lap view va totalmark
            $collection->update($tempBook,array('$set'=>array("view"=>((int)$tempBook["view"]+1),"totalmark"=>(int)$totalmark)));
            
        }

        $newIdUser=new MongoId($idUser);
        $userModel=new Personal_Model_MUser();
        if(!$userModel->isExistedUser($newIdUser))
                return false;
        // thêm cuốn sách hiện tại vào danh sách sách được xem bởi người dùng hiện tại
        if($idUser!='')
        {
            $rating = -1;
            $newIdUser=new MongoId($idUser);
            $newbook = array("id_book"=>$newIdBook,"rating"=>$rating);
            $collection=$db->book_view_history;
            $temp=$collection->findOne(array("id_user"=>$newIdUser));
            // tạo mới
            if($temp==null)
            {
                $query=array("id_user"=>$newIdUser,"listbookid"=>array($newbook));
                $collection->insert($query);
            }
            else    // thêm vào danh sách đã có
            {
                // Kiểm tra trong danh sách đã có cuốn sách này chưa
                foreach($temp["listbookid"] as $book)
                {
                    if($book["id_book"]==$newIdBook)
                    {
                        return;
                    }
                }
                // Thêm cuốn sách hiện tại vào danh sách sách đã xem
                // Danh sach toi da chi co 20 quyen
                if(count($temp["listbookid"])==20)
                {
                    $collection->update($temp,array('$pop'=>array("listbookid"=>-1)));
                }
                $collection->update($temp,array('$push'=>array("listbookid"=>$newbook)));
            }
        }
        
        // Them vao danh sach nhung nguoi co view thay doi
        $collection = $db->new_view_history;

        $temp=$collection->findOne(array("id_user"=>$newIdUser));
        if ($temp == NULL) $collection->insert(array("id_user"=>array($newIdUser)));
        else return;
    }

    // Lấy ngẫu nhiên 15 cuốn sách cùng chủ đề
    // phục vụ cho cho xem sách cùng chủ đề trong trang xem chi tiết
    public function getBookByCatMin($idCat)
    {
        $id=new MongoId($idCat);
        $bookFromBook=$this->getBooksAdvance('book', array("id_category"=>$id), array("Date_added"=>-1), 15,
                array("_id","image","id_author","id_category","name","date_publish","publisher","cost","saleoff"));

        $author=new Admin_Model_MAuthor();
        $bookByCat=array();
        foreach($bookFromBook as $bookTemp)
        {
            $bookInforCommunity=$this->getABook('bookinterest', array("id_book"=>$bookTemp["_id"]), array("sumrating","view"));
            $authorDocument=$author->getAuthor($bookTemp["id_author"]);
            $aBookByCat=array("_id"=>$bookTemp["_id"],"image"=>$bookTemp["image"],
                "id_author"=>$bookTemp["id_author"],"authorname"=>$authorDocument["name"],"id_category"=>$bookTemp["id_category"],
                "name"=>$bookTemp["name"],"date_publish"=>$bookTemp["date_publish"],
                "publisher"=>$bookTemp["publisher"],"cost"=>$bookTemp["cost"],
                "saleoff"=>$bookTemp["saleoff"],
                "sumrating"=>$bookInforCommunity["sumrating"],"view"=>$bookInforCommunity["view"]
                );
            array_push($bookByCat, $aBookByCat);
        }

        return $bookByCat;
        
    }


    // Thêm comment cho cuốn sách. Dùng trên trang xem sách chi tiết
    public function addCommentBook($idbook,$iduser,$content)
    {
        $abook= $this->getABook('bookinterest', array("id_book"=>new MongoId($idbook)), 
                array("_id","comment","sumcomment","view","sumlike","sumrating","sellnumber"));
        if($abook ==null)
        {
            return false;
        }

        $collection=$this->connection->bookstore->bookinterest;
        $id=new MongoId($iduser);
        $user=new Personal_Model_MUser();
        $userInfo=$user->getInfoBasic($id);
        $date=  Zend_Date::now();
        if(isset($abook["comment"]))   // đã có comment
        {
            $sumcomment=(int)($abook["sumcomment"]);
            $sumcomment++;
            $order=0;
            foreach($abook["comment"] as $comment)
            {
                if((int)$comment["stt"]>$order)
                    $order=(int)$comment["stt"];
            }
            $order++;
            // update totalmark
            $totalmark=(int)$abook["view"]+(int)$sumcomment+(int)$abook["sumlike"]
                        +2*(int)$abook["sumrating"]+3*(int)$abook["sellnumber"];
            
            $collection->update($abook,array(
                '$push'=>array("comment"=>array("stt"=>$order,"id_user"=>$id,"content"=>$content,"date"=>$date->__toString())),
                '$set'=>array("sumcomment"=>$sumcomment,"datecomment"=>$this->_function->dateToString($date),"totalmark"=>(int)$totalmark),
                 )
            );
            //$collection->update($abook,array('$set'=>array("sumcomment"=>$sumcomment)));
            //$collection->update($abook,array('$set'=>array("datecomment"=>$date->__toString())));

            return array("stt"=>$order,"id_user"=>$id,"user_name"=>$userInfo["user_name"],
                "user_image"=>$userInfo["image"],"content"=>$content,"date"=>$date->__toString());
        }
        else    // comment đầu tiên
        {
            $collection->update($abook,array('$push'=>array(
                "comment"=>array("stt"=>1,"id_user"=>$id,"content"=>$content,"date"=>$date->__toString())
                 ),
                '$set'=>array("datecomment"=>$this->_function->dateToString($date))
               )
            );
             // update totalmark
            $totalmark=(int)$abook["view"]+1+(int)$abook["sumlike"]
                        +2*(int)$abook["sumrating"]+3*(int)$abook["sellnumber"];
            $collection->update($abook,array('$set'=>array("sumcomment"=>1,"totalmark"=>(int)$totalmark)));
            //$collection->update($abook,array('$set'=>array("datecomment"=>$date->__toString())));
            
            return array("stt"=>1,"id_user"=>$id,"user_name"=>$userInfo["user_name"],
                "user_image"=>$userInfo["image"],"content"=>$content,"date"=>$date->__toString());
        }

        return false;
    }
    //---------------------------------------------------------------------------------------------
    //---------------------------------------------------------------------------------------------

    //---------------------------------------------------------------------------------------------
    //----------------- Chức năng quản lý danh mục sách -------------------------------------------
    //---------------------------------------------------------------------------------------------
    /* $fiels chứa danh sách các trường muốn lấy*/
    public function getAllCategories($fiels=array())
    {
        
        $db=$this->connection->bookstore;
        $collection=$db->category;
        
        if( $fiels == null || count($fiels)==0)
            return $collection->find();
        else
        {
            $filter=array();
            for($i=0;$i<count($fiels);$i++)
            {
               $filter[$fiels[$i]]=true;
            }
            return $collection->find(array(),$filter);
        }
    }

    public function getCategory($idCat='0')
    {
        $db=$this->connection->bookstore;
        $collection=$db->category;

        if( $idCat == '0')
            $document = $collection->findOne();
        else
        {
            $id=new MongoId($idCat);
            $document=$collection->findOne(array("_id"=>$id));
        }

        return $document["name"];
    }

    public function addCategory($nameCat)
    {
        $db=$this->connection->bookstore;
        $collection=$db->category;
        $cats=$collection->find();
        foreach($cats as $cat)
        {
            if(strtolower($cat["name"])==strtolower($nameCat))
                return -1;
        }
        $newCat=array("name"=>$nameCat);
        $collection->insert($newCat);
        return 1;
    }
    public function changeCategory($newName,$idCat)
    {
        $db=$this->connection->bookstore;
        $collection=$db->category;
        $cats=$collection->find();
        foreach($cats as $cat)
        {
            if($cat["name"]==$newName)
                return -1;
        }
        $id=new MongoId($idCat);
        $document=$collection->findOne(array("_id"=>$id));
        $newDocument=array("_id"=>$id,"name"=>$newName);
        $collection->update($document,$newDocument);
        return 1;
    }

    public function deleteCategory($idCat)
    {
        $db=$this->connection->bookstore;
        $collection=$db->category;
        $id=new MongoId($idCat);
        $document=array("_id"=>$id);
        return $collection->remove($document);
    }

    //---------------------------------------------------------------------------------------------
    //------------------------- Chức năng quản lý sách -------------------------------------------
    //---------------------------------------------------------------------------------------------
    public function getAuthors($fiels=array())
    {
        $db=$this->connection->bookstore;
        $collection=$db->author;

        if( $fiels == null || (is_array($fiels) && count($fiels)==0))
            return $collection->find();
        else
        {
            $filter=array();
            for($i=0;$i<count($fiels);$i++)
            {
               $filter[$fiels[$i]]=true;
            }
            return $collection->find(array(),$filter);
        }
    }


    // Hàm này bỏ nhưng để lại phục vụ làm ví dụ về update dữ liệu
    /*public function insertDate()
    {
        $db=$this->connection->bookstore;
        $book=$db->book;
        $newbook=$db->newbook;
        $bestseller=$db->bestseller;

        foreach(($newbook->find()) as $book1)
        {
            $document=$book->findOne(array("_id"=>$book1["id_book"]));
            if(is_array($document) && count($document)>0)
            {
                $newbook->update($book1,array('$set'=>array("date"=>$document["date_added"])));
            }
        }

        foreach(($bestseller->find()) as $book1)
        {
            $document=$book->findOne(array("_id"=>$book1["id_book"]));
            if(is_array($document) && count($document)>0)
            {
                $bestseller->update($book1,array('$set'=>array("date"=>$document["date_added"])));
            }
        }
    }*/

    // nếu $id = 0 hoặc để trống thì lấy tất cả sách trong collection có tên $nameCollection
    // nếu $id !=0 là lấy sách trong collection có id= new MongoId($id);
    public function getBooks($nameCollection,$id=0,$field=array())
    {
        $db=$this->connection->bookstore;
        $collection=$db->$nameCollection;
        
        if(is_int($id) && $id==0 && (is_array($field) && count($field)==0))
        {
            return $collection->find();
        }
        else if(is_int($id) && $id==0 && (is_array($field) && count($field)>0))
        {
            $filter=array();
            for($i=0;$i<count($field);$i++)
            {
               $filter[$field[$i]]=true;
            }

            return $collection->find(array(),$filter);
        }
        else if(!is_int($id) && (is_array($field) && count($field)==0))
        {
            $idMongo=new MongoId($id);
            return $collection->findOne(array("_id"=>$idMongo));
        }
        else
        {
            $filter=array();
            for($i=0;$i<count($field);$i++)
            {
               $filter[$field[$i]]=true;
            }
            $idMongo=new MongoId($id);
            return $collection->findOne(array("_id"=>$idMongo),$filter);
        }
    }

    public function getABook($nameCollection,$query=array(),$field=array())
    {
        $db=$this->connection->bookstore;
        $collection=$db->$nameCollection;

        if(is_array($query) && count($query)==0 && (is_array($field) && count($field)==0))
        {
            return $collection->findOne();
        }
        if(is_array($query) && count($query)==0 && (is_array($field) && count($field)>0))
        {
            $filter=array();
            for($i=0;$i<count($field);$i++)
            {
               $filter[$field[$i]]=true;
            }

            return $collection->findOne(array(),$filter);
        }
        if(is_array($query) && count($query)>0 && (is_array($field) && count($field)==0))
        {
            return $collection->findOne($query);
        }
        else
        {
            $filter=array();
            for($i=0;$i<count($field);$i++)
            {
               $filter[$field[$i]]=true;
            }
            return $collection->findOne($query,$filter);
        }
    }
    
    public function getBooksAdvance($nameCollection,$query=array(),$sort=array(),$limit=0,$fields=array())
    {
        $db=$this->connection->bookstore;
        $collection=$db->$nameCollection;

        $isFilter=FALSE;
        $filter=array();
        if(is_array($fields) && count($fields)>0)
        {
            for($i=0;$i<count($fields);$i++)
            {
               $filter[$fields[$i]]=true;
            }
            $isFilter=TRUE;
        }

        if(is_array($query) && count($query)==0 && is_array($sort) && count($sort)==0 && is_int($limit) && $limit==0)
        {
            if(!$isFilter)
                return $collection->find();
            else
                return $collection->find(array(),$filter);
        }
        else if(is_array($query) && count($query)>0 && is_array($sort) && count($sort)==0 && is_int($limit) && $limit==0)
        {
            if(!$isFilter)
                return $collection->find($query);
            else
                return $collection->find($query,$filter);
        }
        else if(is_array($query) && count($query)==0 && is_array($sort) && count($sort)>0 && is_int($limit) && $limit==0)
        {
            if(!$isFilter)
                return $collection->find()->sort($sort);
            else
                return $collection->find(array(),$filter)->sort($sort);
        }
        else if(is_array($query) && count($query)==0 && is_array($sort) && count($sort)==0 && is_int($limit) && $limit>0)
        {
            if(!$isFilter)
                return $collection->find()->limit($limit);
            else
                return $collection->find(arrya(),$filter)->limit($limit);
        }
        else if(is_array($query) && count($query)>0 && is_array($sort) && count($sort)>0 && is_int($limit) && $limit==0)
        {
            if(!$isFilter)
                return $collection->find($query)->sort($sort);
            else
                return $collection->find($query,$filter)->sort($sort);
        }
        else if(is_array($query) && count($query)>0 && is_array($sort) && count($sort)==0 && is_int($limit) && $limit>0)
        {
            if(!$isFilter)
                return $collection->find($query)->limit($limit);
            else
                return $collection->find($query,$filter)->limit($limit);
        }
        else if(is_array($query) && count($query)==0 && is_array($sort) && count($sort)>0 && is_int($limit) && $limit>0)
        {
            if(!$isFilter)
                return $collection->find()->sort($sort)->limit($limit);
            else
                return $collection->find(array(),$filter)->sort($sort)->limit($limit);
        }
        else
        {
            if(!$isFilter)
                return $collection->find($query)->sort($sort)->limit($limit);
            else
                return $collection->find($query,$filter)->sort($sort)->limit($limit);
        }
    }

    // Lấy tất cả sách có trong csdl
    // phục vụ chức năng tìm kiếm
    public function getAllBookForSearch()
    {
        $bookFromBook=$this->getBooks('book', 0,
                array("_id","id_author","id_category","name"));
        $author=new Admin_Model_MAuthor();
        $book=array();
        foreach($bookFromBook as $bookTemp)
        {
            $authorDocument=$author->getAuthor($bookTemp["id_author"]);
            $aBook=array("_id"=>$bookTemp["_id"],
                "id_author"=>$bookTemp["id_author"],"authorname"=>$authorDocument["name"],
                "id_category"=>$bookTemp["id_category"],"name"=>$bookTemp["name"]
                );
            array_push($book, $aBook);
        }

        return $book;
    }

    // Lấy sách theo danh mục sách
    // phục vụ chức năng tìm kiếm
    public function getBookByCatForSearch($idCat)
    {
        $id=new MongoId($idCat);
        $bookFromBook=$this->getBooksAdvance('book', array("id_category"=>$id), array(), 0,
                array("_id","id_author","id_category","name"));
        $author=new Admin_Model_MAuthor();
        $bookByCat=array();
        foreach($bookFromBook as $bookTemp)
        {
            $authorDocument=$author->getAuthor($bookTemp["id_author"]);
            $aBookByCat=array("_id"=>$bookTemp["_id"],
                "id_author"=>$bookTemp["id_author"],"authorname"=>$authorDocument["name"],
                "id_category"=>$bookTemp["id_category"],"name"=>$bookTemp["name"],
                );
            array_push($bookByCat, $aBookByCat);
        }

        return $bookByCat;
    }


    // Lấy danh sách sách theo id danh mục được truyền vào
    // phục vụ chức năng xem sách theo danh mục 
    public function getBookByCat($idCat,$pagesize,$currentpage,&$total)
    {
        $id=new MongoId($idCat);
        $bookFromBook=$this->getBooksAdvance('book', array("id_category"=>$id), array(), 0,
                array("_id","image","id_author","id_category","name","date_publish","publisher","cost","saleoff"));
        $total=$bookFromBook->count();

        $bookFromBook=$bookFromBook->skip(($currentpage-1)*$pagesize)->limit($pagesize);

        $author=new Admin_Model_MAuthor();
        $bookByCat=array();
        foreach($bookFromBook as $bookTemp)
        {
            $bookInforCommunity=$this->getABook('bookinterest', array("id_book"=>$bookTemp["_id"]), array("sumrating","view"));
            $authorDocument=$author->getAuthor($bookTemp["id_author"]);
            $aBookByCat=array("_id"=>$bookTemp["_id"],"image"=>$bookTemp["image"],
                "id_author"=>$bookTemp["id_author"],"authorname"=>$authorDocument["name"],"id_category"=>$bookTemp["id_category"],
                "name"=>$bookTemp["name"],"date_publish"=>$bookTemp["date_publish"],
                "publisher"=>$bookTemp["publisher"],"cost"=>$bookTemp["cost"],
                "saleoff"=>$bookTemp["saleoff"],
                "sumrating"=>$bookInforCommunity["sumrating"],"view"=>$bookInforCommunity["view"]
                );
            array_push($bookByCat, $aBookByCat);
        }

        return $bookByCat;
    }

    // Lấy thông tin chi tiết về một cuốn sách
    // phục vụ chức năng xem chi tiết sách
    public function getBookDetailById($idBook)
    {
        $docuFromBook=$this->getBooks('book', $idBook,
                array("_id","image","id_author","id_category","name","date_publish","quote","information","publisher","cost","saleoff"));
        if($docuFromBook == null || (is_array($docuFromBook) && count($docuFromBook)==0))
            return array();

        $author=new Admin_Model_MAuthor();
        $docuAuthor=$author->getAuthor($docuFromBook["id_author"]);

        $category=new Admin_Model_MCategory();
        $catName=$category->getCategoryName($docuFromBook["id_category"]);

        $docuInforCommunity=$this->getABook('bookinterest', array("id_book"=>$docuFromBook["_id"]), array());
        if(isset($docuInforCommunity["comment"]) && is_array($docuInforCommunity["comment"]))
        {
            for($i=0;$i<count($docuInforCommunity["comment"]);$i++)
            {
                $comment=$docuInforCommunity["comment"][$i];
                $userModel=new Personal_Model_MUser();
                $user=$userModel->getInfoBasic($comment["id_user"]);
                $comment["user_name"]=$user["user_name"];
                $comment["user_image"]=$user["image"];
                $docuInforCommunity["comment"][$i]=$comment;
            }
        }
        return array("_id"=>$docuFromBook["_id"],"image"=>$docuFromBook["image"],
                "id_author"=>$docuFromBook["id_author"],"authorname"=>$docuAuthor["name"],"catname"=>$catName,"id_category"=>$docuFromBook["id_category"],
                "name"=>$docuFromBook["name"],"date_publish"=>$docuFromBook["date_publish"],
                "publisher"=>$docuFromBook["publisher"],"quote"=>$docuFromBook["quote"],"information"=>$docuFromBook["information"],
                "cost"=>$docuFromBook["cost"],"saleoff"=>$docuFromBook["saleoff"],
                "sumrating"=>$docuInforCommunity["sumrating"],"view"=>$docuInforCommunity["view"],
                "comment"=>$docuInforCommunity["comment"],"rating"=>$docuInforCommunity["rating"]
                );
    }

    // Lấy danh sách sách id tác giả truyền vào
    // phục vụ chức năng lấy sách theo tác giả
    public function getBookByAuthor($idAuthor)
    {
        $id=new MongoId($idAuthor);
        $bookFromBook=$this->getBooksAdvance('book', array("id_author"=>$id), array(), 0,
                array("_id","image","id_author","name","date_publish","publisher","cost","saleoff"));
        $author=new Admin_Model_MAuthor();
        $bookByAuthor=array();
        foreach($bookFromBook as $bookTemp)
        {
            $bookInforCommunity=$this->getABook('bookinterest', array("id_book"=>$bookTemp["_id"]), array("sumrating","view"));
            $authorDocument=$author->getAuthor($bookTemp["id_author"]);
            $aBookByAuthor=array("_id"=>$bookTemp["_id"],"image"=>$bookTemp["image"],
                "id_author"=>$bookTemp["id_author"],"authorname"=>$authorDocument["name"],
                "name"=>$bookTemp["name"],"date_publish"=>$bookTemp["date_publish"],
                "publisher"=>$bookTemp["publisher"],"cost"=>$bookTemp["cost"],
                "saleoff"=>$bookTemp["saleoff"],
                "sumrating"=>$bookInforCommunity["sumrating"],"view"=>$bookInforCommunity["view"]
                );
            array_push($bookByAuthor, $aBookByAuthor);
        }

        return $bookByAuthor;
    }

    public function getNumberBookByAuthor($idAuthor)
    {
        $id=new MongoId($idAuthor);
        $bookFromBook=$this->getBooksAdvance('book', array("id_author"=>$id), array(), 0,
                array("_id"));
        return $bookFromBook->count();
    }


    public function addBook($query,$nameCollection)
    {
        $db=$this->connection->bookstore;
        $collection=$db->$nameCollection;
        if($nameCollection=='book')
        {
            $find=array(array(),array("name","id_author"));
            $cursor=$collection->find($find);
            foreach($cursor as $document)
            {
                if(strtolower($document["name"])== strtolower($query["name"]) &&
                   $document["id_author"] == $query["id_author"]) // đã tồn tại cuốn sách này
                   return -1;
            }
        }
        $collection->insert($query);
        $doReturn=$collection->findOne($query);
        return $doReturn["_id"];
    }

    public function addAuthor($name)
    {
        $db=$this->connection->bookstore;
        $collection=$db->author;
        $cursor=$collection->find(array(),array("_id"=>true,"name"=>true));
        foreach($cursor as $document)
        {
            if(strtolower($document["name"])==  strtolower($name))
            {
                return $document["_id"];
            }
        }

        $doAuthor=array("name"=>$name);
        $collection->insert($doAuthor);

        $doReturn=$collection->findOne($doAuthor);
        return $doReturn["_id"];
    }

    private function stripVietnameseAccent ($inputString)
    {
        // Bảng dịch ký tự không dấu bao gồm 2 bảng mã cho unicode và windows cp 1258
        $trans = array (
                        'á' => 'a', 'à' => 'a', 'ả' => 'a', 'ã' => 'a', 'ạ' => 'a',
                        'Á' => 'A', 'À' => 'A', 'Ả' => 'A', 'Ã' => 'A', 'Ạ' => 'A',

            'â' => 'a', 'ấ' => 'a', 'ầ' => 'a', 'ẩ' => 'a', 'ẫ' => 'a', 'ậ' => 'a',
            'Â' => 'A', 'Ấ' => 'A', 'À' => 'A', 'Ẩ' => 'A', 'Ẫ' => 'A', 'Ậ' => 'A',

            'ă' => 'a', 'ắ' => 'a', 'ằ' => 'a', 'ẳ' => 'a', 'ẵ' => 'a', 'ặ' => 'a',
            'Ă' => 'A', 'Ắ' => 'A', 'Ằ' => 'A', 'Ẳ' => 'A', 'Ẵ' => 'A', 'Ặ' => 'A',

                        'é' => 'e', 'è' => 'e', 'ẻ' => 'e', 'ẽ' => 'e', 'ẹ' => 'e',
                        'É' => 'E', 'È' => 'E', 'Ẻ' => 'E', 'Ẽ' => 'E', 'Ẹ' => 'E',

            'ê' => 'e', 'ế' => 'e', 'ề' => 'e', 'ể' => 'e', 'ễ' => 'e', 'ệ' => 'e',
            'Ê' => 'E', 'Ế' => 'E', 'Ề' => 'E', 'Ể' => 'E', 'Ễ' => 'E', 'Ệ' => 'E',

                        'í' => 'i', 'ì' => 'i', 'ỉ' => 'i', 'ĩ' => 'i', 'ị' => 'i',
                        'Í' => 'I', 'Ì' => 'I', 'Ỉ' => 'I', 'Ĩ' => 'I', 'Ị' => 'I',

                        'ó' => 'o', 'ò' => 'o', 'ỏ' => 'o', 'õ' => 'o', 'ọ' => 'o',
                        'Ó' => 'O', 'Ò' => 'O', 'Ỏ' => 'O', 'Õ' => 'O', 'Ọ' => 'O',

            'ơ' => 'o', 'ớ' => 'o', 'ờ' => 'o', 'ở' => 'o', 'ỡ' => 'o', 'ợ' => 'o',
            'Ơ' => 'O', 'Ớ' => 'O', 'Ờ' => 'O', 'Ở' => 'O', 'Ỡ' => 'O', 'Ợ' => 'O',

            'ô' => 'o', 'ố' => 'o', 'ồ' => 'o', 'ổ' => 'o', 'ỗ' => 'o', 'ộ' => 'o',
            'Ô' => 'O', 'Ố' => 'O', 'Ồ' => 'O', 'Ổ' => 'O', 'Ỗ' => 'O', 'Ộ' => 'O',

                        'ú' => 'u', 'ù' => 'u', 'ủ' => 'u', 'ũ' => 'u', 'ụ' => 'u',
                        'Ú' => 'U', 'Ù' => 'U', 'Ủ' => 'U', 'Ũ' => 'U', 'Ụ' => 'U',

            'ư' => 'u', 'ứ' => 'u', 'ừ' => 'u', 'ử' => 'u', 'ữ' => 'u', 'ự' => 'u',
            'Ư' => 'U', 'Ứ' => 'U', 'Ừ' => 'U', 'Ử' => 'U', 'Ữ' => 'U', 'Ự' => 'U',

                        'ý' => 'y', 'ỳ' => 'y', 'ỷ' => 'y', 'ỹ' => 'y', 'ỵ' => 'y',
                        'Ý' => 'Y', 'Ỳ' => 'Y', 'Ỷ' => 'Y', 'Ỹ' => 'Y', 'Ỵ' => 'Y',

            'đ' => 'd',
            'Đ' => 'D',

            ' ' => '-',
            ':' => '-',
            ',' => '-',
            '.' => '-',
            '"' => '-',
            '\'' => '-',
            '?' => '-',
            '(' => '-',
            ')' => '-',
            '!' => '-',
            '@' => '-',
            '#' => '-',
            '$' => '-',
            '%' => '-',
            '^' => '-',
            '&' => '-',
            '*' => '-',
            '{' => '-',
            '}' => '-',
            '[' => '-',
            ']' => '-',
            '/' => '-',
            '>' => '-',
            '<' => '-',
            '`' => '-',
            '~' => '-',
            '+' => '-',
            '=' => '-',
            '|' => '-',
            );

        // Dịch Tiếng Việt có dấu thành không dấu theo 2 bảng mã Unicode va window cp 1258
        return strtr ( $inputString, $trans ); // Chuỗi đã được bỏ dấu
    }
   
    public function searchBooks($idCat,$textSearch,$pagesize,$currentpage,&$total)
    {
        $pathLucene="../public/lucene-data";
        $textSearch=$this->stripVietnameseAccent($textSearch);
        while($textSearch[0]=='-')
        {
            $textSearch=substr($textSearch, 1);
        }
        $textSearch=strtr($textSearch,array('-'=>' ') );
        //var_dump($textSearch);
        $index=Zend_Search_Lucene::open($pathLucene);
        if($idCat=='0') // tìm trong tất cả sách
        {
            $query='name:'.$textSearch .' OR nameauthor:'.$textSearch;
            $hits=$index->find($query);
        }
        else            // tìm trong một danh mục cụ thể
        {
            $query='id_category:'.$idCat.' AND (name:'.$textSearch .' OR nameauthor:'.$textSearch.')';
            $hits=$index->find($query);
            //var_dump($hits);
            if(count($hits)==0)
            {
                $query='name:'.$textSearch .' OR nameauthor:'.$textSearch;
                $hits=$index->find($query);
            }
        }
        $total=count($hits);
        $author=new Admin_Model_MAuthor();

        $book=array();
        $max=(count($hits)>$currentpage*$pagesize?$currentpage*$pagesize:count($hits));
        for($i=($currentpage-1)*$pagesize;$i<$max;$i++)
        {
            $bookFromBook=$this->getBooks('book', $hits[$i]->_id,
                    array("_id","image","id_author","id_category","name","date_publish","publisher","cost","saleoff") );
            $bookInforCommunity=$this->getABook('bookinterest', array("id_book"=>new MongoId($hits[$i]->_id)), array("sumrating","view"));
            $authorDocument=$author->getAuthor($bookFromBook["id_author"]);
            $aBook=array("_id"=>$bookFromBook["_id"],"image"=>$bookFromBook["image"],
                "id_author"=>$bookFromBook["id_author"],"authorname"=>$authorDocument["name"],"id_category"=>$bookFromBook["id_category"],
                "name"=>$bookFromBook["name"],"date_publish"=>$bookFromBook["date_publish"],
                "publisher"=>$bookFromBook["publisher"],"cost"=>$bookFromBook["cost"],
                "saleoff"=>$bookFromBook["saleoff"],
                "sumrating"=>$bookInforCommunity["sumrating"],"view"=>$bookInforCommunity["view"]
                );

            array_push($book, $aBook);
        }
        return $book;
    }

    public function rateBook($uid, $bid, $rating = -1){


        $db = $this->connection->bookstore;
        $collection = $db->book_view_history;

        $mUid = new MongoId($uid);
        $mBid = new MongoId($bid);

        // user da tung view quyen sach chua
        $select = array("id_user"=>$mUid,'listbookid.id_book'=>$mBid);
        $docView = $collection->findOne($select);
        if($docView !=NULL){
            $query = array('$set'=>array('listbookid.$.rating'=>$rating));
            $collection->update($select,$query);

            // Them vao danh sach nhung nguoi co view thay doi
            $collection = $db->new_view_history;
            $temp=$collection->findOne(array("id_user"=>$mUid));
            if ($temp == NULL) $collection->insert(array("id_user"=>array($mUid)));

            /*
             *  Cap nhat rating ve quyen sach
             * - Quyen sach da ton tai, khi cap nhat view
             * - Kiem tra user da rating chua   - chua, them vao mang rating
             *                                  - da rate, cap nhat gia tri rating
             */

            $collection = $db->bookinterest;
            $select = array("id_book"=>$mBid,'rating.id_user'=>$mUid);

            $temp = $collection->findOne(array("id_book"=>$mBid));
            if($temp == null){
                return -3;
                //$query = array("id_book"=>$mBid,"rating"=>array(array("id_user"=>$mUid,"value_rating"=>$rating)));
                //$collection->insert($query);
            }
            else
            if(isset($temp["rating"])){
            //var_dump($temp);
                $exist = false;
                foreach($temp["rating"] as $rate_time){
                    if($rate_time["id_user"]==$mUid) {
                        $query = array('$set'=>array('rating.$.value_rating'=>$rating));
                        $collection->update($select,$query);
                        $exist = true;
                        break;
                    }
                }
                if(!$exist) $collection->update(array("id_book"=>$mBid),array('$push'=>array("rating"=>array("id_user"=>$mUid,"value_rating"=>$rating))));
            }
            else {
                
                $select = array("id_user"=>$mUid,"value_rating"=>$rating);
                $query = array('$set'=>array("rating"=>array($select)));
                $collection->update(array("id_book"=>$mBid),$query);
            }

            /*
             * Tinh lai rating 1 quyen sach
             */
             try{
                $docBook = $collection->findOne(array("id_book"=>$mBid));
                $total = 0;
                foreach ($docBook["rating"] as $arating){
                    $total +=  (int)$arating["value_rating"];
                }
                $nrating = count($docBook["rating"]);
                $aver = (int)($total/$nrating + 0.5);
                // update totalmark
                $totalmark=(int)$docBook["view"]+(int)$docBook["sumcomment"]+(int)$docBook["sumlike"]
                            +2*(int)$aver+3*(int)$docBook["sellnumber"];
                $query = array('$set'=>array("sumrating"=>$aver,"totalmark"=>(int)$totalmark));
                $collection->update(array("id_book"=>$mBid),$query);

                //var_dump($aver);
             }
             catch(Exception $ex){
                 echo "<script>alert('error')</script>";
             }

            return 1;
        }
        else return -2;
    }

    public function getBasicInfoBook($bid)
    {
        if(!$this->isExistBook($bid))
        {
            return array();
        }

        $author=new Admin_Model_MAuthor();
        $bookFromBook=$this->getBooks('book', $bid,
                    array("_id","image","id_author","id_category","name","date_publish","publisher","cost","saleoff") );
        $bookInforCommunity=$this->getABook('bookinterest', array("id_book"=> new MongoId($bid)), array("sumrating","view"));
        $authorDocument=$author->getAuthor($bookFromBook["id_author"]);
        $aBook=array("_id"=>$bookFromBook["_id"],"image"=>$bookFromBook["image"],
            "id_author"=>$bookFromBook["id_author"],"authorname"=>$authorDocument["name"],"id_category"=>$bookFromBook["id_category"],
            "name"=>$bookFromBook["name"],"date_publish"=>$bookFromBook["date_publish"],
            "publisher"=>$bookFromBook["publisher"],"cost"=>$bookFromBook["cost"],
            "saleoff"=>$bookFromBook["saleoff"],
            "sumrating"=>$bookInforCommunity["sumrating"],"view"=>$bookInforCommunity["view"]
            );
        return $aBook;
    }

    public function getBookForPay($bid)
    {
        if(!$this->isExistBook($bid))
        {
            return array();
        }

        $author=new Admin_Model_MAuthor();
        $bookFromBook=$this->getBooks('book', $bid,
                    array("_id","id_author","name","cost","saleoff") );
        $cost=(int)$bookFromBook["cost"]*(100-(int)$bookFromBook["saleoff"])/100;
        $authorDocument=$author->getAuthor($bookFromBook["id_author"]);
        $aBook=array("_id"=>$bookFromBook["_id"],
            "id_author"=>$bookFromBook["id_author"],"authorname"=>$authorDocument["name"],
            "name"=>$bookFromBook["name"],"cost"=>$cost);
        return $aBook;
    }

    public function getRecommendBook($uid)
    {
        $userModel=new Personal_Model_MUser();
        if(!$userModel->isExistedUser($uid))
            return array();
        $recommendTemp=$this->getABook('recommendbook', array("id_user"=>new MongoId($uid)));
        $recommendBook=array();

        if($recommendTemp==null)
        {
            
            return array();
        }
        foreach($recommendTemp["listbookid"] as $idbook)
        {
            $documentBook=$this->getBooks('book', $idbook, array("_id","image","name","id_author","cost","saleoff"));
            $documentBookInterest=$this->getABook('bookinterest',array("id_book"=>$idbook), array("sumrating","view"));

            $author=new Admin_Model_MAuthor();
            $nameAuthor=$author->getAuthor($documentBook["id_author"]);

            $aRecommendBook=array("_id"=>$documentBook["_id"],"image"=>$documentBook["image"],"name"=>$documentBook["name"],"author"=>$nameAuthor["name"],"id_author"=>$documentBook["id_author"],
                "cost"=>$documentBook["cost"],"saleoff"=>$documentBook["saleoff"],"sumrating"=>$documentBookInterest["sumrating"],"view"=>$documentBookInterest["view"]);

            array_push($recommendBook, $aRecommendBook);
        }

        return $recommendBook;
    }
    public function test($namecollection)
    {
        $db=$this->connection->bookstore;
        $collection=$db->$namecollection;
        $document=$collection->findOne();
        return $document["_id"];
    }

    public function getNumberBook($nameCollection)
    {
        $collection=$this->connection->bookstore->$nameCollection;
        return $collection->find()->count();
    }

    // chỉ được chạy một lần để thay đổi định dạng ngày tháng trong
    // collection book, newbook, bestseller, phục vụ cho sắp xếp khi đọc ra
    // sau khi chạy xong thì comment lại hàm này và không được chạy lại nữa
    public function updateDateOfBook()
    {
        $bookCollection=$this->connection->bookstore->book;
        $function =new Default_Model_MFunction();
        foreach($bookCollection->find() as $abook)
        {
            $date=$abook["date_added"];
            $date=$function->standardStringDate($date);
            $bookCollection->update($abook,array('$set'=>array("date_added"=>$date)));
        }

        $bookCollection=$this->connection->bookstore->newbook;
        foreach($bookCollection->find() as $abook)
        {
            $date=$abook["date"];
            $date=$function->standardStringDate($date);
            $bookCollection->update($abook,array('$set'=>array("date"=>$date)));
        }

        $bookCollection=$this->connection->bookstore->bestseller;
        foreach($bookCollection->find() as $abook)
        {
            $date=$abook["date"];
            $date=$function->standardStringDate($date);
            $bookCollection->update($abook,array('$set'=>array("date"=>$date)));
        }
    }
}
?>
